#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

//黄牛抢票，创建多个线程充当黄牛,创建一个全局变量作为票的数量

pthread_mutex_t g_mutex;
int ticket=100;
void *Scalper(void *arg){
    while(1){
        pthread_mutex_lock(&g_mutex);
        if(ticket>0){
            printf("%p:抢到了一张票:%d\n",(void*)pthread_self(),ticket);
            ticket--;
            pthread_mutex_unlock(&g_mutex);
            usleep(1);
        }
        else{
            //没有票了就退出
            //一旦在函数内进行了加锁，就要在任意有可能退出的地方之前进行解锁
            pthread_mutex_unlock(&g_mutex);
            pthread_exit(NULL);
        }
    }
    return NULL;
}
int main(){
    int ret;
    pthread_t tid[4];

    pthread_mutex_init(&g_mutex,NULL);
    for(int i=0;i<4;i++){
        ret=pthread_create(&tid[i],NULL,Scalper,NULL);
        if(ret!=0){
            perror("create thread fail!\n");
            return -1;
        }
    }
    for(int i=0;i<4;i++){
        pthread_join(tid[i],NULL);
    }
    pthread_mutex_destroy(&g_mutex);
    return 0;
}
